from . import admins_bp
from .forms.link import EditForm
from ...models import Link, db
from ...helper import redirect_back
from flask import render_template, flash, request


@admins_bp.route('/link')
def link_select():
    query = Link.query
    title = request.args.get('title', type=str, default=None)
    if title:
        query = query.filter(Link.site_name.like('%{}%'.format(title.strip())))
    record = query.paginate()
    return render_template('link_select.html', page_title='友情链接', record=record)


@admins_bp.route('/link/create', methods=['GET', 'POST'])
def link_create():
    form = EditForm()
    if form.validate_on_submit():
        with db.auto_commit():
            _l = Link()
            _l.set_fields(form.data)
            db.session.add(_l)
        flash('新增成功', 'success')
        return redirect_back('admins.link_select')
    return render_template('link_edit.html', page_title='新增友链', form=form)


@admins_bp.route('/link/<int:link_id>/modify', methods=['GET', 'POST'])
def link_modify(link_id):
    _l = Link.query.get_or_404(link_id)
    form = EditForm(**_l.__dict__)
    if form.validate_on_submit():
        with db.auto_commit():
            _l.set_fields(form.data)
        flash('更新成功', 'success')
        return redirect_back('admins.link_select')
    return render_template('link_edit.html', page_title='更新友链', form=form)


@admins_bp.route('/link/<int:link_id>/delete', methods=['POST'])
def link_delete(link_id):
    link = Link.query.get_or_404(link_id)
    db.session.delete(link)
    db.session.commit()
    flash('删除成功', 'success')
    return redirect_back('admins.link_select')

